package com.acme.concurrent.point;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Gregory Sobko
 */
public class Tracker {
    private final Map<String, Point> locations;

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public Tracker(Map<String, Point> locations) {
        this.locations = deepCopy(locations);
    }

    public Point getLocation(String id){
        try{
            lock.readLock().lock();
            if(locations.containsKey(id)){
                return new Point(locations.get(id));
            }else{
                return null;
            }
        }finally {
            lock.readLock().unlock();
        }
    }

    public Map<String, Point> getLocations(){
        try{
            lock.readLock().lock();
            return Collections.unmodifiableMap(deepCopy(locations));
        }finally {
            lock.readLock().unlock();
        }
    }

    public void setLocation(String id, Point point){
        try{
            lock.writeLock().lock();
            locations.put(id, new Point(point));
        }finally {
            lock.writeLock().unlock();

        }
    }

    private Map<String,Point> deepCopy(Map<String, Point> source) {
        Map<String,Point> result = new HashMap<String,Point>();
        for(Map.Entry<String,Point> pair: source.entrySet()){
            result.put(pair.getKey(), new Point(pair.getValue()));
        }
        return result;
    }

}
